//
//  CourseDetailViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/9/15.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "CourseDetailViewController.h"
#import "INtroduceCourseTableViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "CourseDetailHeadView.h"
#import "AllHeader.h"
#import "PayViewController.h"
#import "CourseDetailModel.h"
/// 微信分享
#import "ShareViewController.h"

#import <UIImageView+WebCache.h>

// http://arts1hangzhou.oss-cn-hangzhou.aliyuncs.com/iPad%20Pro%20-%20Reveal.mp4?OSSAccessKeyId=btSqdMIkhrmma4ZQ&amp;Expires=1441884417&amp;Signature=rh%2BLdxOZjbXtkgqgW5LsbuGmYmU%3D
#define  cURL @"http://arts1hangzhou.oss-cn-hangzhou.aliyuncs.com/iPad%20Pro%20-%20Reveal.mp4"

// 课程详情
#define  cDURL @"http://arts1.dlab.com.cn/app/courseinfo"

// 点赞
#define goodURL @"http://arts1.dlab.com.cn/app/zan"

// 生成渐变开始颜色
#define kGradientStart [UIColor colorWithRed:230 % 256 / 255.0 green:0 % 256 / 255.0 blue:155 % 256 / 255.0 alpha:1]

// 生成渐变结束颜色
#define kGradientEnd [UIColor colorWithRed:150 % 256 / 255.0 green:10 % 256 / 255.0 blue:155 % 256 / 255.0 alpha:1]


@interface CourseDetailViewController ()

// 自定义navigation视图
@property (nonatomic, strong) CourseDetailHeadView *navigationview;

// 视频播放器
@property (nonatomic, strong) MPMoviePlayerController *playController;

// 课程介绍
@property (nonatomic, strong) UIButton *leftBTN;

// 视频详情
@property (nonatomic, strong) UIButton *rightBTN;

// tabbar上的遮盖视图
@property (nonatomic, strong) UIView *bottomView;

// 视图底部的tabbar按钮
@property (nonatomic, strong) UIButton *tabBarBTN;

// 课程介绍页面
@property (nonatomic, strong) INtroduceCourseTableViewController *courseIVC;

// 分享选项页面
@property (nonatomic, strong) ShareViewController *shareVC;

// model类
@property (nonatomic, strong) CourseDetailModel *course;

//  生成渐变层
@property (strong, nonatomic) CAGradientLayer *gradientLayer;

//  生成会员卡
@property (nonatomic, strong) UIView *backgroundView;

//  生成渐变层
@property (nonatomic, strong) UIView *gradientView;

//  会员条款
@property (nonatomic, strong) UILabel *arts1Label;
@property (nonatomic, strong) UILabel *cardName;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *dearCustomor;
@property (nonatomic, strong) UILabel *list1;
@property (nonatomic, strong) UILabel *list2;
@property (nonatomic, strong) UILabel *list3;
@property (nonatomic, strong) UIImageView *iamgeVIew;
@property (nonatomic, strong) UIButton *payButten;

@end

@implementation CourseDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    [self requestData];
    
    [self createNavigationBar];
    [self createPlayView];
    [self createCourseIntroduceview];
    [self createButtons];
    [self createTabBarView];
    [self createShareView];
}

- (void)setModel:(CourseModel *)model{
    _model = model;
    _ID = model.Id;
}

// 网络请求
- (void)requestData{
        AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
        manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
        manage.responseSerializer = [AFHTTPResponseSerializer serializer];
        
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    NSString *uid = userDic[@"data"][@"uid"];
    NSString *key = userDic[@"data"][@"key"];
    
    //请求参数
   NSDictionary *pardic = @{@"courseId":_ID,@"uid":uid,@"key":key};
    
    NSLog(@"uid === %@ ***** key %@",uid, key);
    
        [manage POST:cDURL parameters:pardic
             success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             // 请求成功的时候调用这个block
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             //返回的状态
             int index = [dic[@"status"] intValue];
             if (index == 1) {
                 NSDictionary *dict = dic[@"data"];
                 _course = [[CourseDetailModel alloc] init];
                 [_course setValuesForKeysWithDictionary:dict];
             }
             
             NSLog(@"视频详情*****返回数据 ： %@", dic);
             dispatch_async(dispatch_get_main_queue(), ^{
                 _navigationview.course = _course;
                 if ([_course.isAllow intValue]) {
                     [self addURLToPlay];
                 } else {
                     [MBProgressHUD show:@"您还没有权限视频观看" icon:nil view:self.view];
                     [self showPicture];
                 }
             });
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];

}

/**
 *  用户具有视频播放权限之后,给视频播放器添加url
 */
- (void)addURLToPlay{
    NSString *url = [_course.videoUrl componentsSeparatedByString:@"?"][0];
    _playController.contentURL = [NSURL URLWithString:[url stringByAppendingString:@"?"]];
}

// 自定义navigationbar
- (void)createNavigationBar{
    _navigationview = [[CourseDetailHeadView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 44)];
    _navigationview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_navigationview];
    //  给返回按钮添加点击事件
    [_navigationview.backButton addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
    //  给分享按钮添加点击事件
    [_navigationview.shareBTN addTarget:self action:@selector(shareMessage:) forControlEvents:(UIControlEventTouchUpInside)];
}

// 后退
- (void)back:(UIButton *)btn{
    _bottomView.hidden = YES;
    [_playController stop];
    [self.navigationController popViewControllerAnimated:YES];
 
}


// 创建分享选项卡
- (void)createShareView{
    _shareVC = [[ShareViewController alloc] init];
    [self.view addSubview:_shareVC.view];
    _shareVC.view.frame = CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT);
}


// 分享
- (void)shareMessage:(UIButton *)btn{
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        _shareVC.view.frame = CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark  ---  视频播放
- (void)createPlayView{
    _playController = [[MPMoviePlayerController alloc] init];
    _playController.view.frame = CGRectMake(0, _navigationview.bottom, SCREEN_WIDTH, 201 * HEIGHT);
    _playController.controlStyle = MPMovieControlStyleDefault;
    [self.view addSubview:_playController.view];
    [_playController prepareToPlay];
}

/**
 *  创建视频播放器的占位符，当用户没有权限时展示图片
 */
- (void)showPicture{
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:_playController.view.bounds];
    [imageview sd_setImageWithURL:[NSURL URLWithString:_model.photo]];
    [_playController.view addSubview:imageview];
}


// 课程介绍、视屏详情
- (void)createButtons{
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, _playController.view.bottom, SCREEN_WIDTH, 40)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [UIView viewWideForShadowColor:whiteView];
   // [UIView viewShadowColor:whiteView];
    
    // 下载
    _leftBTN = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _leftBTN.frame = CGRectMake(0, 0, whiteView.width / 2.0 - 0.5, whiteView.height);
    [_leftBTN setTitle:@"  下载" forState:(UIControlStateNormal)];
    [_leftBTN setImage:[UIImage imageNamed:@"downloadButton"] forState:(UIControlStateNormal)];
    _leftBTN.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [_leftBTN setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    [_leftBTN addTarget:self action:@selector(introduceCourse:) forControlEvents:(UIControlEventTouchUpInside)];
    [whiteView addSubview:_leftBTN];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(whiteView.width / 2.0 -0.5, 5, 1, 30)];
    line.backgroundColor = sFONTCOLOR;
    [whiteView addSubview:line];
    
    // 称赞
    _rightBTN = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _rightBTN.frame = CGRectMake(_leftBTN.right + 1, 0, whiteView.width / 2.0 - 0.5, whiteView.height);
    [_rightBTN setTitleColor:sFONTCOLOR forState:(UIControlStateNormal)];
    [_rightBTN setTitle:@"  称赞" forState:(UIControlStateNormal)];
    _rightBTN.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [_rightBTN setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    [_rightBTN setImage:[UIImage imageNamed:@"tabGoodButton"] forState:(UIControlStateNormal)];
    [_rightBTN addTarget:self action:@selector(introduceMedia:) forControlEvents:(UIControlEventTouchUpInside)];
    [whiteView addSubview:_rightBTN];
    
    [self.view addSubview:whiteView];
}


// 下载
- (void)introduceCourse:(UIButton *)btn{
    [_leftBTN setTitleColor:lFONTCOLOR forState:(UIControlStateNormal)];
    [_rightBTN setTitleColor:sFONTCOLOR forState:(UIControlStateNormal)];
    
}

// 称赞
- (void)introduceMedia:(UIButton *)btn{
    [_leftBTN setTitleColor:sFONTCOLOR forState:(UIControlStateNormal)];
    [_rightBTN setTitleColor:lFONTCOLOR forState:(UIControlStateNormal)];
    [self requestGoodDataAndStatus];
}

//请求数据
- (void)requestGoodDataAndStatus
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *pardic = @{@"id":_ID,@"type":@"course"};
    
    [manage GET:goodURL parameters:pardic
        success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 请求成功的时候调用这个block
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            // 请求返回的状态，当status = 1 时有数据
            NSInteger status = [dic[@"status"] integerValue];
            if (status == 1) {
                //信息提示框
                [MBProgressHUD show:@"操作成功" icon:nil view:self.view];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // 请求失败的时候调用调用这个block
            NSLog(@"请求失败");
        }];
    
}

// 创建视频介绍页面
- (void)createCourseIntroduceview{
    _courseIVC = [[INtroduceCourseTableViewController alloc] init];
    [self.view addSubview:_courseIVC.tableView];
    _courseIVC.tableView.frame = CGRectMake(0 , _playController.view.bottom + 40 , SCREEN_WIDTH, SCREEN_HEIGHT - _playController.view.bottom - 89);
}

//  创建tabbarview视图
- (void)createTabBarView{
    // tabbar上面的遮盖视图
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 49)];
    _bottomView.backgroundColor = lFONTCOLOR;
    
    // 播放页面底部的 “支持｜更多” 按钮
    _tabBarBTN = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _tabBarBTN.frame = CGRectMake(SCREEN_WIDTH/2.0 - 45, 9.5, 90, 30);
    _tabBarBTN.titleLabel.font = [UIFont systemFontOfSize:16];
    _tabBarBTN.backgroundColor = lFONTCOLOR;
    _tabBarBTN.tintColor = sFONTCOLOR;
    [_tabBarBTN setTitle:@"支持 ｜ 更多" forState:(UIControlStateNormal)];
    [_tabBarBTN addTarget:self action:@selector(tapToPay) forControlEvents:(UIControlEventTouchUpInside)];
    
    [_bottomView addSubview:_tabBarBTN];
    [self.tabBarController.tabBar addSubview:_bottomView];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{    
    [_iamgeVIew removeFromSuperview];
    [self createTabBarView];
}


- (void)tapToPay{
    // 关闭视频
    [_playController stop];
    
    UIImage *screenIamge = [self.view screenShotFromView:self.view];
    _iamgeVIew = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _iamgeVIew.image = [screenIamge boxblurImageWithBlur:0];

    [self payView];

    [UIView animateWithDuration:0.4 delay:0 options:(UIViewAnimationOptionCurveEaseInOut) animations:^{
        [_bottomView removeFromSuperview];
        
        _backgroundView.frame = CGRectMake(25, SCREEN_HEIGHT / 2 - 210 / 2 - 50, SCREEN_WIDTH - 50, 210);
        [self.view addSubview:_iamgeVIew];
        
        [_iamgeVIew addSubview:_backgroundView];
        _iamgeVIew.image = [screenIamge boxblurImageWithBlur:0.8];
    } completion:^(BOOL finished) {
        nil;
    }];
    
    [UIView animateWithDuration:0.8 delay:1.2 options:(UIViewAnimationOptionCurveEaseInOut) animations:^{
//        _gradientView.frame = CGRectMake(0, _backgroundView.size.height - 65, _backgroundView.size.width - 0, 0.5);
        _arts1Label.alpha = 0;
        _gradientView.frame = CGRectMake(0, 0, _gradientView.size.width, _gradientView.size.height - 70);
//        [UIView viewRediusForLeftAndReightOfBottom:_gradientView withRedius:0];
        _cardName.frame = CGRectMake(15, _backgroundView.size.height - 55, 150, 20);
        _cardName.alpha = 1;
        _priceLabel.frame = CGRectMake(14,_cardName.bottom + 0, 150, 20);
        _priceLabel.alpha = 1;
        _dearCustomor.frame = CGRectMake(15,15, _backgroundView.size.width - 30, 20);
        _dearCustomor.alpha = 1;
        _list1.frame = CGRectMake(15, 70, _backgroundView.size.width - 30, 20);
        _list1.alpha = 1;
        _list2.frame = CGRectMake(15, _list1.bottom + 0, _backgroundView.size.width - 30, 20);
        _list2.alpha = 1;
        _list3.frame = CGRectMake(15, _list2.bottom + 0, _backgroundView.size.width - 30, 20);
        _list3.alpha = 1;
        _payButten.frame = CGRectMake(_backgroundView.size.width - 15 - 65, _backgroundView.size.height - 17 - 37, 65, 37);
        _payButten.alpha = 1;
    } completion:^(BOOL finished) {
        nil;
    }];

}

- (void)payView{
    _backgroundView = [[UIView alloc] initWithFrame:CGRectMake(25, SCREEN_HEIGHT, SCREEN_WIDTH - 50, 210)];
    _backgroundView.layer.cornerRadius = 15;
    _backgroundView.backgroundColor = [UIColor whiteColor];

    [UIView viewWideForShadowColor:_backgroundView];
    [self.view addSubview:_backgroundView];
    
    _gradientView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _backgroundView.size.width, _backgroundView.size.height - 0)];
    
    UIBezierPath *maskPath=  [UIBezierPath bezierPathWithRoundedRect:_gradientView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft |UIRectCornerBottomRight cornerRadii:CGSizeMake(15, 15)];
    CAShapeLayer *maskLayer=[[CAShapeLayer alloc] init];
    maskLayer.frame = _gradientView.bounds;
    maskLayer.path=maskPath.CGPath;
    _gradientView.layer.mask=maskLayer;
    _gradientView.layer.masksToBounds=YES;
    
    
    [_backgroundView addSubview:_gradientView];
    
    //初始化渐变层
    self.gradientLayer = [CAGradientLayer layer];
    self.gradientLayer.frame = _gradientView.bounds;
    [_gradientView.layer addSublayer:self.gradientLayer];
    
    //设置渐变颜色方向
    self.gradientLayer.startPoint = CGPointMake(0, 0);
    self.gradientLayer.endPoint = CGPointMake(1, 1);
    
    //设定颜色组
    self.gradientLayer.colors = @[(__bridge id)kGradientStart.CGColor,
                                  (__bridge id)kGradientEnd.CGColor];
    
    //设定颜色分割点
    self.gradientLayer.locations = @[@(0.5f) ,@(1.0f)];
    
    _arts1Label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _gradientView.size.width, _gradientView.size.height)];
    _arts1Label.text = @"Arts1";
    _arts1Label.font = [UIFont boldSystemFontOfSize:48];
    _arts1Label.textColor = [UIColor whiteColor];
    [_arts1Label setTextAlignment:(NSTextAlignmentCenter)];
    [_gradientView addSubview:_arts1Label];
    
    _cardName = [[UILabel alloc] initWithFrame:CGRectMake(230, _backgroundView.size.height - 55, 150, 20)];
    _cardName.text = @"会员卡";
    _cardName.font = [UIFont boldSystemFontOfSize:18];
    _cardName.alpha = 0;
    _cardName.textColor = kGradientStart;
    [_backgroundView addSubview:_cardName];
    
    _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(250,_cardName.bottom + 0, 150, 20)];
    _priceLabel.text = @"￥199";
    _priceLabel.font = [UIFont boldSystemFontOfSize:16];
    _priceLabel.alpha = 0;
    _priceLabel.textColor = kCustomColor(150, 150, 150, 1);
    [_backgroundView addSubview:_priceLabel];
    
    _dearCustomor = [[UILabel alloc] initWithFrame:CGRectMake(65,15, _backgroundView.size.width - 30, 20)];
    _dearCustomor.text = @"您将得到我们以下真诚的服务：";
    _dearCustomor.alpha = 0;
    _dearCustomor.font = [UIFont boldSystemFontOfSize:15];
//    _dearCustomor.textColor = kCustomColor(40, 40, 50, 1);
    _dearCustomor.textColor = [UIColor whiteColor];
    [_backgroundView addSubview:_dearCustomor];
    
    _list1 = [[UILabel alloc] initWithFrame:CGRectMake(95, 70, _backgroundView.size.width - 30, 15)];
    _list1.text = @"实时在线客服";
    _list1.alpha = 0;
    _list1.font = [UIFont italicSystemFontOfSize:13];
//    _list1.textColor = kCustomColor(150, 150, 150, 1);
    _list1.textColor = [UIColor whiteColor];
    [_backgroundView addSubview:_list1];
    
    _list2 = [[UILabel alloc] initWithFrame:CGRectMake(125, _list1.bottom + 0, _backgroundView.size.width - 30, 15)];
    _list2.text = @"最新考试动态提醒";
    _list2.alpha = 0;
    _list2.font = [UIFont italicSystemFontOfSize:13];
//    _list2.textColor = kCustomColor(150, 150, 150, 1);
    _list2.textColor = [UIColor whiteColor];
    [_backgroundView addSubview:_list2];
    
    _list3 = [[UILabel alloc] initWithFrame:CGRectMake(155, _list2.bottom + 0, _backgroundView.size.width - 30, 15)];
    _list3.text = @"上千部视频无限次学习";
    _list3.alpha = 0;
    _list3.font = [UIFont italicSystemFontOfSize:13];
//    _list3.textColor = kCustomColor(150, 150, 150, 1);
    _list3.textColor = [UIColor whiteColor];
    [_backgroundView addSubview:_list3];
    
    _payButten = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];
    _payButten.frame = CGRectMake(_backgroundView.size.width, _backgroundView.size.height - 17 - 37, 65, 37);
    _payButten.layer.cornerRadius = 5;
    _payButten.layer.masksToBounds = YES;
    _payButten.alpha = 0;
    _payButten.backgroundColor = kCustomColor(245, 165, 35, 1);
    [_payButten setTitle:@"去支付" forState:(UIControlStateNormal)];
    _payButten.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [_payButten setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [_backgroundView addSubview:_payButten];
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
